package Common;
/**
 * Alphabet reads an alphabet from a specified file and stores it in a vector it
 */
import java.util.HashMap;
import java.util.Vector;

public class Alphabet {

	// The alphabet
	String[] alpha;
	
	// For storing a symbol to position in the alphabet mapping
	private HashMap<String, Integer> symbolToPosition;

	/**
	 * Alphabet constructor
	 *
	 * @param a the alphabet
	 */
	public Alphabet(String[] a) {
		this.alpha = a;
		symbolToPosition = new HashMap<String, Integer>();
		for (int i = 0; i < this.alpha.length; i++) {
			symbolToPosition.put(this.alpha[i], i);
		}
	}

	/**
	 * Alphabet constructor
	 *
	 * @param filename the name of the file where the alphabet is defined
	 */
	public Alphabet(String filename) throws Exception {
		this(readFile(filename));
	}

	/**
	 * Accessor for the alphabet
	 *
	 * @return the alphabet
	 */
	public String[] getAlphabet() {
		return this.alpha;
	}

	/**
	 * Does the given symbol appear within the alphabet
	 *
	 * @param symbol the symbol to look for within the pattern
	 * @return True if symbol is in pattern - otherwise false
	 */
	public boolean contains(String symbol) {

		return symbolToPosition.containsKey(symbol);
	}

	/**
	 * Read the alphabet from a file into a vector.
	 *
	 * @param filename The filename to read the alphabet from.
	 * @return alphabet A vector containing the alphabet.
	 * @throws Exception file exceptions
	 */
	private static String[] readFile(String filename) throws Exception {
		Vector<String> alphabet = new Vector<String>();
		// Open the file for reading
	    java.io.BufferedReader in = new java.io.BufferedReader(new java.io.FileReader(filename));
	    String s;
	    int n = 0;
	    // Read from the file while more lines to read
	    do {
	    	s = in.readLine();
	    	if (s != null) {
	    		alphabet.add(s);
	    		n++;
	    	}
	    } while(s != null);
	    in.close();
		// Conversion buffer
		String[] buffer = new String[n];
		// Convert vector to array
		return alphabet.toArray(buffer);
	}
	
	/**
	 * Alphabet represented as a string.
	 * 
	 * @return String with alphabet symbols.
	 */
	public String toString() {
		
		String str = "[";
		
		// Build string
		for(int i = 0; i < alpha.length; i++) {
			
			str += alpha[i];
			
			if(i < alpha.length -1) {
				str += ", ";
			}
		}
		
		str += "]";
		
		return str;
	}

}
